package cn.xiaobai.http;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author yangdaji
 * @Date 2023/11/29
 * @PackageName cn.xiaobai.http
 * @ClassName ResponseHander
 */
public class ResponseHeader {

    private String protocol;

    private int code;

    private String msg;


    private int content_length;


    private Map<String, String> handlerMap = new HashMap<String, String>() {{
        put(ContentType.key, ContentType.TEXT_HTML);
    }};

    public ResponseHeader(int code) {
        this("HTTP/1.1", code, StatusEnum.getMsg(code));
    }

    public ResponseHeader(int code, String msg) {
        this("HTTP/1.1", code, msg);
    }

    public ResponseHeader(String protocol, int code, String msg) {
        this.protocol = protocol;
        this.code = code;
        this.msg = msg;
    }

    public enum StatusEnum {
        Ok(200, "OK");

        private int code;
        private String msg;

        StatusEnum(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }

        public static String getMsg(int code) {
            for (StatusEnum statusEnum : StatusEnum.values()) {
                if (statusEnum.getCode() == code) {
                    return statusEnum.getMsg();
                }
            }
            return null;
        }

        public int getCode() {
            return code;
        }

        public String getMsg() {
            return msg;
        }
    }

    public static final class ContentType {

        public static final String key = "Content-Type";

        public static final String TEXT_HTML = "text/html;charset=utf-8";
        public static final String APPLICATION_JSON = "application/json";
        public static final String TEXT_XML = "text/xml";
    }


    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setContent_length(int content_length) {
        this.content_length = content_length;
    }

    public void setHandlerMap(Map<String, String> handlerMap) {
        this.handlerMap = handlerMap;
    }

    @Override
    public String toString() {
        // HTTP/1.1 200 OK xxx
        return protocol + " " + code + " " + msg + "\r\n" + mapToStr() + "\r\n\r\n";
    }

    public String mapToStr() {
        StringBuilder str = new StringBuilder();
        handlerMap.forEach((key, val) -> {
            str.append(key).append(":").append(val).append("\n");
        });
        return str.toString();
    }
}
